package com.aefottt.struggle_star.adapter;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.aefottt.struggle_star.R;
import com.aefottt.struggle_star.bean.SubTaskBean;
import com.aefottt.struggle_star.bean.TaskBean;
import com.aefottt.struggle_star.util.DisplayUtil;
import com.aefottt.struggle_star.view.AchieveView;

import java.util.List;

public class SubTaskRecyclerAdapter extends RecyclerView.Adapter<SubTaskRecyclerAdapter.TodoListViewHolder> {
    private final List<SubTaskBean> subTaskBeans;
    private final TaskBean taskBean;
    private final Context context;

    private TodoListViewHolder lastHolder;

    public SubTaskRecyclerAdapter(Context context, TaskBean taskBean, List<SubTaskBean> subTaskBeans) {
        this.subTaskBeans = subTaskBeans;
        this.taskBean = taskBean;
        this.context = context;
    }

    @NonNull
    @Override
    public TodoListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_todo_list_sub, parent, false);
        return new TodoListViewHolder(view) {
        };
    }

    @Override
    public void onBindViewHolder(@NonNull TodoListViewHolder holder, int position) {
        if (position == subTaskBeans.size()) {
            holder.et.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus){
                    holder.et.setText("");
                    holder.et.setTextColor(Color.BLACK);
                    startEtClickAnim(holder.ivAdd, holder.achieveView, true);
                    holder.achieveView.setCanClick(false); // 添加新的子任务时圆圈不可点击
                }else {
                    String title = holder.et.getText().toString();
                    if (TextUtils.isEmpty(title)){
                        // 最后一行输入为空，恢复Add New状态
                        startEtClickAnim(holder.ivAdd, holder.achieveView, false);
                        holder.et.setText(R.string.text_add_sub);
                        holder.et.setTextColor(context.getResources().getColor(R.color.selected_color));
                    }else {
                        // 输入不为空，保添加New SubTask
                        SubTaskBean subTaskBean = new SubTaskBean(taskBean.getDataId(),
                                taskBean.getSubTasks().size(), title, 0);
                        subTaskBean.save();
                        subTaskBeans.add(subTaskBean);
                        notifyItemInserted(subTaskBeans.size() - 1);
                        setLastAddItem();
                    }
                }
            });
            lastHolder = holder;
            setLastAddItem();
        } else {
            SubTaskBean subTaskBean = subTaskBeans.get(position);
            holder.delete.setVisibility(View.VISIBLE);
            holder.delete.setOnClickListener(v -> deleteItem(position));
            // 设置是否已完成，view内自带invalidate()
            holder.achieveView.setAchieved(subTaskBeans.get(position).getIsAchieved());
            DisplayUtil.changeEtContent(holder.et, subTaskBeans.get(position).getTitle(),
                    subTaskBeans.get(position).getIsAchieved());
            holder.achieveView.setOnAchievedViewListener(state -> {
                if (state == AchieveView.ACHIEVED_STATE) {
                    subTaskBean.setIsAchieved(1);
                } else if (state == AchieveView.NOT_ACHIEVED_STATE) {
                    subTaskBean.setIsAchieved(0);
                }
                subTaskBean.save();
                DisplayUtil.changeEtContent(holder.et, subTaskBeans.get(position).getTitle(),
                        subTaskBeans.get(position).getIsAchieved());
            });
            holder.et.setOnFocusChangeListener((v, hasFocus) -> {
                if (!hasFocus){
                    String title = holder.et.getText().toString();
                    if (TextUtils.isEmpty(title)){
                        // 其他行输入为空，则删除该行
                        deleteItem(position);
                    }else {
                        // 修改SubTask内容
                        SubTaskBean newSubTask = subTaskBeans.get(position);
                        newSubTask.setTitle(title);
                        newSubTask.save();
                        notifyItemChanged(position);
                    }
                }
            });
        }
        holder.et.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_BACK){
                holder.et.clearFocus();
                if (keyCode == KeyEvent.KEYCODE_ENTER){
                    DisplayUtil.hideSoftInput(context);
                }
                return true;
            }
            return false;
        });
    }

    /**
     * 单独设置最后一行View
     */
    private void setLastAddItem(){
        if (lastHolder == null){
            return;
        }
        lastHolder.ivAdd.setVisibility(View.VISIBLE);
        lastHolder.achieveView.setVisibility(View.GONE);
        lastHolder.et.setText(R.string.text_add_sub);
        lastHolder.et.setTextColor(context.getResources().getColor(R.color.selected_color));
        lastHolder.delete.setVisibility(View.GONE);
        lastHolder.splitView.setVisibility(View.GONE);
        startEtClickAnim(lastHolder.ivAdd, lastHolder.achieveView, false);
    }

    /**
     * 开启点击EditText时左侧图标的动画效果
     *
     * @param state true：iv->achieveView  false:achieveView->iv
     */
    private void startEtClickAnim(ImageView iv, AchieveView achieveView, boolean state) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(state ? iv : achieveView, "alpha", 1.0f, 0);
        animator.setDuration(360);
        animator.start();
        animator.addUpdateListener(animation -> {
            float val = (float) animation.getAnimatedValue();
            if (state) {
                iv.setAlpha(val);
                achieveView.setVisibility(View.VISIBLE);
                achieveView.setAlpha(1.0f - val);
                if (val == 0) {
                    iv.setVisibility(View.GONE);
                }
            } else {
                achieveView.setAlpha(val);
                iv.setVisibility(View.VISIBLE);
                iv.setAlpha(1.0f - val);
                if (val == 0) {
                    achieveView.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 删除某一条数据
     *
     * @param position 数据的位置
     */
    public void deleteItem(int position) {
        subTaskBeans.get(position).delete();
        subTaskBeans.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public int getItemCount() {
        return subTaskBeans.size() + 1;
    }

    static class TodoListViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAdd, delete;
        AchieveView achieveView;
        EditText et;
        View splitView;

        public TodoListViewHolder(@NonNull View itemView) {
            super(itemView);
            ivAdd = itemView.findViewById(R.id.iv_add_new_sub);
            delete = itemView.findViewById(R.id.iv_add_sub_delete);
            achieveView = itemView.findViewById(R.id.achieved_view_add_sub);
            et = itemView.findViewById(R.id.et_add_sub_title);
            splitView = itemView.findViewById(R.id.view_split);
        }
    }
}
